//
//  LinkEffect.cpp
//  client
//
//  Created by will on 17/07/2017.
//
//

#include "LinkEffect.hpp"
#include "LineEffect.hpp"


LinkEffect* LinkEffect::create()
{
    auto ret = new (std::nothrow) LinkEffect();
    bool ok = ok = ret->init();

    if(ok)
    {
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return nullptr;
}

bool LinkEffect::init()
{
    if(Node::init())
    {
        return true;
    }

    return false;
}

LinkEffect::LinkEffect()
:_lineNode(nullptr),
_startNode(nullptr),
_endNode(nullptr)
{
    
    
}

LinkEffect::~LinkEffect()
{
    
}

void LinkEffect::setLineEffect(LineEffect* node)
{
    if(_lineNode)
    {
        _lineNode->removeFromParent();
        _lineNode=nullptr;
    }
    
    _lineNode=node;
    addChild(node);
}

void LinkEffect::setStartNode(Node* node)
{
    if(_startNode)
    {
        _startNode->removeFromParent();
        _startNode=nullptr;
    }

    _startNode=node;
    addChild(node);
}

void LinkEffect::setEndNode(Node* node)
{
    if(_endNode)
    {
        _endNode->removeFromParent();
        _endNode=nullptr;
    }
    _endNode=node;
    addChild(node);
}


void LinkEffect::setStartPos(float x,float y)
{
    _start.x=x;
    _start.y=y;
    _start = convertToNodeSpace(_start);
    if(_lineNode)
    {
        _lineNode->setStartPos(_start);
    }
    _updateLinkPos();
}

void LinkEffect::setEndPos(float x,float y)
{
    _end.x=x;
    _end.y=y;
    _end = convertToNodeSpace(_end);
    if(_lineNode)
    {
        _lineNode->setEndPos(_end);
    }
    
    _updateLinkPos();
}

void LinkEffect::setStartPos(const Vec2&start){
    setStartPos(start.x,start.y);
}

void LinkEffect::setEndPos(const Vec2&end){
    setEndPos(end.x,end.y);
}

void LinkEffect::_faceTo(Node* node,const Vec2& from,const Vec2& to)
{
    Vec2 dir=(to-from).getNormalized();
    float A;
    if(dir.y<=0){
        A=acosf(dir.x)*180/M_PI;
    }else{
        A=(2*M_PI-acosf(dir.x))*180/M_PI;
    }
    node->setRotation(A);
}

void LinkEffect::_updateLinkPos()
{
    if(_startNode)
    {
        _startNode->setPosition(_start);
        _faceTo(_startNode,_end,_start);
    }
    
    if(_endNode)
    {
        _endNode->setPosition(_end);
        _faceTo(_endNode,_start,_end);
    }
}

